<?php

namespace App\Http\Controllers\Admin\Task;

use App\Enums\RewardEnum;
use App\Enums\TaskEnum;
use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;    //引用http请求类
use App\Response\Response;

class TaskConfigController extends BaseController {

    /**
     * @api {post} /task/config 任务配置-创建
     * @apiVersion 0.1.0
     * @apiName 任务管理-任务配置-创建
     * @apiGroup 任务管理
     *
     * @apiParam {string} name                      任务名称 必传
     * @apiParam {string} desc                      任务描述 必传
     * @apiParam {number} type_id                   类型id 必传
     * @apiParam {number} module_id                 模块id 必传
     * @apiParam {number} open_day                  开放时间 必传
     * @apiParam {number} target_limit              条件值 必传
     * @apiParam {number} cycle_days                循环周期 必传
     * @apiParam {number} reward_id                 奖品id 必传
     * @apiParam {number} reward_number             奖品数量 必传
     * @apiParam {number} reward_type               奖品大类 1：礼包 2： 道具 必传
     *
     * @apiSuccessExample 成功响应
     *
     *      {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function create(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'name' => 'required|string|max:255',
                'desc' => 'required|string|max:255',
                'type_id' => 'required|numeric|integer|exists:mysql.ln_task_type,id',
                'module_id' => 'required|numeric|exists:mysql.ln_task_module,id',
                'open_day' => 'required|numeric|min:0|max:4200000000',
                'target_limit' => 'required|numeric|min:0|max:4200000000',
                'cycle_days' => 'required|numeric|min:0|max:4200000000',
                'reward_id' => 'required|numeric|min:0|max:2100000000',
                'reward_number' => 'required|numeric|min:1|max:4200000000',
                'reward_type' => 'required|numeric|in:1,2',
            ]);
        if ($v->fails()) throw new BasicException(10001, getValidateMessage($v->messages()));

        $res = app('repo_task');

        $params = $request->input();
        if ($params["reward_type"] == RewardEnum::REWARD_BIG_TYPE_ITEM) {
            $item = app("model_reward_item")->where("id", $params['reward_id'])->first();
            if (empty($item)) {
                throw new BasicException(10001, "未发现id为" . $params['reward_id'] . "的道具！");
            }
        } else {
            $bag = app("model_reward")->where("id", $params['reward_id'])->first();
            if (empty($bag)) {
                throw new BasicException(10001, "未发现id为" . $params['reward_id'] . "的礼包！");
            }
        }

        if (in_array($params['type_id'], [
            TaskEnum::TASK_TYPE_RECHARGE_MONEY,
            TaskEnum::TASK_TYPE_RECHARGE_DAILY_MONEY
        ])) {
            $targetLimit = $params['target_limit'] * TaskEnum::TASK_RATIO;
            $targetLimit = intval($targetLimit);
        } else {
            $targetLimit = $params['target_limit'];
        }
        $params['target_limit'] = $targetLimit;
        $params['add_time'] = time();
        $params['update_time'] = time();

        $rows = $res->addConfig($params);
        if (!$rows) {
            throw new BasicException(10001, "插入失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {delete} /task/config 任务配置-删除
     * @apiVersion 0.1.0
     * @apiName 任务管理-任务配置-删除
     * @apiGroup 任务管理
     *
     * @apiParam {string} ids                       字符串分割的id 必传
     *
     * @apiSuccessExample 成功响应
     *
     *      {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function del(Request $request) {
        //参数校验
        try {
            $this->validate($request, [
                'ids' => 'required|string',
            ]);

        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $idsStr = $request->input("ids");
        $idsArr = explode("," , $idsStr);

        $rows = app('repo_task')->delConfig($idsArr);
        if (!$rows) {
            throw new BasicException(10001, "删除失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {put} /task/config 任务配置-修改
     * @apiVersion 0.1.0
     * @apiName 任务管理-任务配置-修改
     * @apiGroup 任务管理
     *
     *
     * @apiParam {int} id
     * @apiParam {string} name                      任务名称 必传
     * @apiParam {string} desc                      任务描述 必传
     * @apiParam {number} type_id                   类型id 必传
     * @apiParam {number} module_id                 模块id 必传
     * @apiParam {number} open_day                  开放时间 必传
     * @apiParam {number} target_limit              条件值 必传
     * @apiParam {number} cycle_days                循环周期 必传
     * @apiParam {number} reward_id                 奖品id 必传
     * @apiParam {number} reward_number             奖品数量 必传
     * @apiParam {number} reward_type               奖品大类 1：礼包 2： 道具 必传
     *
     * @apiSuccessExample 成功响应
     *
     *      {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function update(Request $request) {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'id' => 'required|integer',
                'name' => 'required|string|max:255',
                'desc' => 'required|string|max:255',
                'type_id' => 'required|numeric|integer|exists:mysql.ln_task_type,id',
                'module_id' => 'required|numeric|exists:mysql.ln_task_module,id',
                'open_day' => 'required|numeric|min:0|max:4200000000',
                'target_limit' => 'required|numeric|min:0|max:4200000000',
                'cycle_days' => 'required|numeric|min:0|max:4200000000',
                'reward_id' => 'required|numeric|min:0|max:2100000000',
                'reward_number' => 'required|numeric|min:1|max:4200000000',
                'reward_type' => 'required|numeric|in:1,2',
            ]
        );
        if ($v->fails()) throw new BasicException(10001, getValidateMessage($v->messages()));

        $res = app('repo_task');

        $params = $request->input();
        $id = $params['id'];

        if ($params["reward_type"] == RewardEnum::REWARD_BIG_TYPE_ITEM) {
            $item = app("model_reward_item")->where("id", $params['reward_id'])->first();
            if (empty($item)) {
                throw new BasicException(10001, "未发现id为" . $params['reward_id'] . "的道具！");
            }
        } else {
            $bag = app("model_reward")->where("id", $params['reward_id'])->first();
            if (empty($bag)) {
                throw new BasicException(10001, "未发现id为" . $params['reward_id'] . "的礼包！");
            }
        }

        if (in_array($params['type_id'], [
            TaskEnum::TASK_TYPE_RECHARGE_MONEY,
            TaskEnum::TASK_TYPE_RECHARGE_DAILY_MONEY
        ])) {
            $targetLimit = $params['target_limit'] * TaskEnum::TASK_RATIO;
            $targetLimit = intval($targetLimit);
        } else {
            $targetLimit = $params['target_limit'];
        }
        $params['target_limit'] = $targetLimit;
        $params['update_time'] = time();

        $rows = $res->saveConfig(["id" => $id], $params);
        if (!$rows) {
            throw new BasicException(10001, "更新失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {get} /task/config 任务配置-列表
     * @apiVersion 0.1.0
     * @apiName 任务管理-任务配置-列表
     * @apiGroup 任务管理
     *
     * @apiParam {number} page 当前页数 可选
     * @apiParam {number} perPage 分页容量 可选
     *
     *
     * @apiSuccessExample 成功响应
     *
     *
    {
    "code": 200,
    "data": {
        "list": [
            {
                "id(序号)": 31,
                "name(任务名称)": "童年记忆",
                "desc(任务说明)": "参与一次抢糖果",
                "type_id(任务类型id)": 11,
                "task_type_name(任务类型名称)": "每日参与抢糖果次数",
                "module_id(模块id)": 1,
                "task_module_name(模块名称)": "新手任务",
                "open_day(开放时间)": 1,
                "target_limit(达成条件)": 1,
                "reward_name(赠送物品)": 1,
                "reward_type(赠送物品类别 1：道具 2：礼包)": 1,
                "reward_number(赠送物品数量)": 1,
                "cycle_days(循环周期)": 1
            }
        ],
        "meta": {
                "page": 1,
                "limit": 10,
                "next": null,
                "total": 1
        },
        "header": {
            "module_map(模块选择范围)": {
                "1": "每日任务",
                "2": "新手任务"
            },
            "type_map(类型选择范围)": {
                "1": "新手每日汇总任务",
                "2": "新手礼包任务"
            }
        }
     }
     *
     *
     */
    public function list(Request $request) {
        //参数校验
        try {
            $this->validate($request, [
                'perPage' => 'filled|numeric',
                'page' => 'filled|numeric',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $list = app('repo_task')->getConfigQueryList($request->input());

        return Response::sendList($list, [], [
            "type_map" => TaskEnum::TASK_TYPE_NAME_MAP,
            "module_map" => TaskEnum::TASK_MODULE_NAME_MAP,
        ]);
    }


}
